package cn.codeartist.springboot.component.http.proxy.impl;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpStatus;
import org.springframework.http.RequestEntity;
import org.springframework.web.client.HttpServerErrorException;

/**
 * 阿里哨兵代理实现
 *
 * @author 艾江南
 * @date 2019/7/18
 */
public class SentinelHttpProxy extends DefaultHttpProxy {

    @Override
    protected <T> T doRequest(RequestEntity<?> requestEntity, Class<T> responseType, ParameterizedTypeReference<T> complexResponseType) {
        Entry entry = null;
        try {
            entry = SphU.entry(beanName);
            return super.doRequest(requestEntity, responseType, complexResponseType);
        } catch (BlockException e) {
            throw new HttpServerErrorException(HttpStatus.INTERNAL_SERVER_ERROR, "sentinel block", null, DEFAULT_CHARSET);
        } finally {
            if (entry != null) {
                entry.exit();
            }
        }
    }
}
